package org.wz.complex.work.controller.upload.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.wz.complex.work.bean.Res;

import java.io.FileOutputStream;

@RestController
@RequestMapping("/upload/file/common")
public class FileCommonController {

    @Value("${upload.tmp}")
    private String uploadTmp;

    @PostMapping("/upload")
    public Res upload(@RequestParam("file") MultipartFile file) {
        try {
            String name = file.getOriginalFilename();
            String suffix = FileUtil.getSuffix(name);
            long now = System.currentTimeMillis();
            String last = SecureUtil.sha256(now + "_" + name) + now + "." + suffix;
            @Cleanup FileOutputStream fos = new FileOutputStream(uploadTmp + last);
            IoUtil.copy(file.getInputStream(), fos);
            return Res.ok(last);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
